package com.xx.controller;

import com.xx.entity.R;
import com.xx.enums.HttpEnum;
import com.xx.exception.BusinessException;
import org.apache.log4j.Logger;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class GlobalException {
    private static final Logger logger = Logger.getLogger(GlobalException.class);
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e , HttpServletRequest request){
        logger.error("请求地址{"+request.getRequestURI()+"},"+"{"+request.getMethod()+"}请求参数有误"
        +e.getBindingResult().getFieldError().getDefaultMessage());
        return R.fail(HttpEnum.VALIDATE_ERROR.getCode(), e.getBindingResult().getFieldError().getDefaultMessage());
    }

    //校验请求方式异常
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,HttpServletRequest request){
        logger.error("请求地址{"+request.getRequestURI()+"},"+"不支持{"+request.getMethod()+"}请求");
        return R.fail(HttpEnum.BAD_METHOD.getCode(),HttpEnum.BAD_METHOD.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public R handBusinessException(BusinessException e,HttpServletRequest request){
        logger.error("请求地址{"+request.getRequestURI()+"},"+"{"+request.getMethod()+"}请求");
        return R.fail(e.getCode(),e.getMessage());
    }
}
